フィルターのクリア

Info

この質問は閉じられています。 編集または回答するには再度開いてください。

c++ problem with the following code can't display the odds num

1 回表示 (過去 30 日間)
ka kei yeung
ka kei yeung 2020 年 5 月 16 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
#include<stdio.h>
// main function
int main(void){
// declare strings
int nums[11] = {1,2,3,4,5,6,7,8,9,10,11};
char odds[20], evens[20];
// setup indexes to track current index of arrays.
int odd_index, even_index, num_index, remainder, i;
char curr_num;
num_index=0;
odd_index=0;
even_index=0;
remainder=0;
for(i = 1; i < 10; i++){
curr_num = nums[i];
remainder = curr_num %2;
if (remainder == 0) {
evens[even_index] = curr_num;
even_index++;
}else{
odds[odd_index] = curr_num;
odd_index++;
}
}
printf("%s is the odd nums \n", odds);
return 0;
}

回答 (1 件)

Walter Roberson
Walter Roberson 2020 年 5 月 16 日
編集済み: Walter Roberson 2020 年 5 月 16 日
To be able to display output in a C function called from MATLAB, you need to use https://www.mathworks.com/help/matlab/apiref/mexprintf.html mexPrintf() instead of printf()
You will also need to build the interface properly in order to call the code from MATLAB; see https://www.mathworks.com/help/matlab/call-mex-files-1.html
Also, since you are building a character vector, you should be careful to store printable characters in it. You are storing the binary value of the integers such as 3 into the odds array, where it will become char(3) rather than '3' . And remember your numbers go up to 11, so if you want printable characters you need two characters for 10 and 11. And remember a seperator between the characters.
  1 件のコメント
James Tursa
James Tursa 2020 年 5 月 18 日
And the strings are not null-terminated, so the printf can run off the end of the array into invalid memory.

この質問は閉じられています。

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by